<?php

/**
 * car.php
 *
 * Author: netman
 * DateTime:  2023/10/09 11:37
 */
class Service_Api_Car extends Contract_Api_Product
{
    use Trait_Api_Car;
    use Trait_Api_Common;

    /**
     * 类型ID
     */
    const TYPE_ID = 3;

    /**
     * @var Service_Api_Fenxiao
     */
    private $fenxiao_service = null;

    public function __construct()
    {
        $this->fenxiao_service = new Service_Api_Fenxiao();
    }

    /**
     * 产品搜索
     * @param array $params
     * @return array
     * User: netman
     * Date: 2023/9/11 17:47
     */
    function search(array $params = array()): array
    {
        $status = true;
        $mid = $params['mid'];
        $use_type = $params['use_type'];
        $time_desc = $params['time_desc'];
        $dest_id = $params['dest_id'];
        $price_id = (int)$params['price_id'];
        $sort_type = (int)($params['sorttype']);
        $attr_id = $params['attrid'];
        $page = (int)($params['page']);
        $page = $page ? $page : 1;
        $pagesize = (int)($params['pagesize']);
        $pagesize = $pagesize ? $pagesize : 5;
        $keyword = $params['keyword'];
        $carkindid = (int)($params['car_kind_id']);
        if ( ! $dest_id) {
            $builder = DB::select(DB::expr('`sline_car`.*,(IFNULL(`sline_car`.bookcount,0)+IFNULL(d.sell,0)) AS sellnum'))
                ->from('car')
                ->distinct(true)
                ->join(DB::expr("(SELECT sum(dingnum) as sell,`sline_member_order`.productautoid FROM `sline_member_order` WHERE `sline_member_order`.typeid=3 GROUP BY `sline_member_order`.productautoid) AS d"),
                    'left')
                ->on(DB::expr('d.productautoid'), '=', 'car.id')
                ->join(array('allorderlist', 'b'), 'left')
                ->on("car.id", '=', 'b.aid')
                ->on('b.typeid', '=', self::TYPE_ID)
                ->on('car.webid', '=', 'b.webid')

                ->join(array('car_suit_price', 'cup'), 'left')
                ->on("cup.carid", '=', 'car.id')

                ->where('car.ishidden', '=', 0)
                ->and_where('car.status', '=', 3);
        } else {
            $builder = DB::select(DB::expr('`sline_car`.*,(IFNULL(`sline_car`.bookcount,0)+IFNULL(d.sell,0)) AS sellnum'))
                ->from('car')
                ->distinct(true)
                ->join(DB::expr("(SELECT sum(dingnum) as sell,`sline_member_order`.productautoid FROM `sline_member_order` WHERE `sline_member_order`.typeid=3 GROUP BY `sline_member_order`.productautoid) AS d"),
                    'left')
                ->on(DB::expr('d.productautoid'), '=', 'car.id')
                ->join(array('kindorderlist', 'b'), 'left')
                ->on("car.id", '=', 'b.aid')
                ->on('b.typeid', '=', self::TYPE_ID)
                ->on('car.webid', '=', 'b.webid')

                ->join(array('car_suit_price', 'cup'), 'left')
                ->on("cup.carid", '=', 'car.id')

                ->where('car.ishidden', '=', 0)
                ->and_where('car.status', '=', 3);
        }


        //按目的地搜索
        if ($dest_id && $dest_id != '0') {
            $builder->and_where(DB::expr(" and FIND_IN_SET(".$dest_id.",sline_car.kindlist)"));
        }

        $time_desc = json_decode($time_desc,true);
        if($use_type==0){
            $get_time_desc  = $this->get_time_desc($use_type,$time_desc);
            $builder->and_where(DB::expr(" and sline_cup.day >= {$get_time_desc['start_time']} and sline_cup.day <= {$get_time_desc['end_time']} "));
        }else{
            $get_time_desc  = $this->get_time_desc($use_type,$time_desc);
            $builder->and_where(DB::expr(" and sline_cup.day >= {$get_time_desc['start_time']} and sline_cup.day <= {$get_time_desc['end_time']} "));
        }

        $builder->and_where('car.use_type','=',$use_type);

        //价格区间
        if ($price_id) {
            $price_arr = DB::select()->from('car_pricelist')->where('id', '=', $price_id)->execute()->current();
            if ( ! empty($price_arr)) {
                $builder->and_where(DB::expr("  AND sline_car.price BETWEEN {$price_arr['min']} AND {$price_arr['max']}"));
            }
        }
        //按属性
        if ( ! empty($attr_id)) {
            $builder->and_where(DB::expr($this->get_attr_where($attr_id)));
        }
        //关键词
        if ( ! empty($keyword)) {
            $builder->and_where(DB::expr(' and sline_car.title like '.'"%'.$keyword.'%"'));
        }
        if ( ! empty($carkindid) && $carkindid != 0) {
            $builder->and_where('car.carkindid', '=', $carkindid);
        }
        //排序
        if ( ! empty($sort_type)) {
            switch($sort_type) {
                case 1://价格升序
                    $builder->order_by(DB::expr("sline_car.price asc"));
                    break;
                case 2://价格降序
                    $builder->order_by(DB::expr("sline_car.price desc"));
                    break;
                case 3://销量降序
                    $builder->order_by('sellnum', 'desc');
                    break;
                case 4://推荐
                    $builder->order_by(DB::expr("sline_car.recommendnum desc"));
                    break;
            }

        }

        //总数量
        $total = $builder
            ->execute()
            ->count();
        //是否超限判断
        $total_page = (int)ceil($total / $pagesize);
        if (($total_page > 0 and intval($page) > $total_page) or ($total_page == 0 and $page > 1)) {
            $status = false;
        }
        if ($page && $pagesize) {
            $offset = St_Page::offset($page, $pagesize);
            $builder->offset($offset)->limit($pagesize);
        }
        $arr = $builder->execute()->as_array();
        $arr = $this->format_car($arr, $mid);
        return array(
            'total' => $total,
            'list' => $arr,
            'status' => $status
        );

    }

    /**日期处理
     * @param $type 租车 包车
     * @param $time_desc 包车 {\"start_time\":\"2023-12-08 10:00\",\"days\":\"3\"} 租车 {\"start_time\":\"2023-12-08 10:00\",\"end_time\":\"2023-12-09 10:01\"}
     * @return array
     * @throws Exception
     */
    public function get_time_desc($type,$time_desc){
        if($type==0){
            $days = $time_desc['days'];
            $startDate = new DateTime($time_desc['start_time']);
            $startDate->add(new DateInterval('P'.($days-1).'D'));
            $start_time=strtotime($time_desc['start_time']);
            $end_time = strtotime($startDate->format('Y-m-d'));//结束当天
        }else{
            $days = strtotime($time_desc['end_time']) - strtotime($time_desc['start_time']);
            $days = ceil($days/60/60/24);//超过1分钟就算一天
            $start_time = date('Y-m-d',strtotime($time_desc['start_time']));
            $start_time = strtotime($start_time);
            $end_time = $start_time+60*60*24*($days-1);//结束当天
        }
        return compact('days','start_time','end_time');
    }

    /**
     * 产品详情
     * @param array $params
     * @return array
     * @throws Kohana_Exception
     * User: netman
     * Date: 2023/9/11 16:39
     */
    function info(array $params = array()): array
    {
        $id = $params['product_id'];
        $mid = $params['mid'];


        $info = DB::select(
            'id', 'title', 'litpic', 'content', 'shownum', 'tagword', 'keyword', 'description',
            'carkindid', 'usedyears', 'attrid','supplierlist' , 'piclist', 'phone', 'notice', 'iconlist', 'satisfyscore',
            'bookcount', 'jifenbook_id', 'jifentprice_id', 'contractid', 'gain_address', 'return_address', 'seatnum',
            'maxseatnum', 'displayorder', 'usedyears', 'sellpoint', 'price', 'status','use_type'
        )
            ->from('car')
            ->where('id', '=', $id)
            ->execute()
            ->current();
        if (!$info) {
            throw new Exception('车辆不存在或已下架');
        }

        $uni_img = Model_Uniapp_Images::get_img_list(self::TYPE_ID,2);
        if(isset($uni_img['litpic'][$info['id']])){
            $info['litpic'] = $uni_img['litpic'][$info['id']];
            $info['piclist'] = $uni_img['piclist'][$info['id']];
        }
        //产品图片
        $piclist = Product::pic_list($info['piclist']);
        $p = array();
        foreach ($piclist as &$pic)
        {
            $pi = $this->img_url($pic[0], 750, 750);
            array_push($p, $pi);
        }
        if(empty($p)){
            $p[0]= $this->img_url('');
        }
        $info['piclist'] = $p;
        //属性列表
        $info['attrlist'] = Model_Car::car_attr($info['attrid']);

        $info['price'] = Model_Car::get_minprice($info['id'], array('info' => $info));

        //点评数
        $info['commentnum'] = Model_Comment::get_comment_num($info['id'], self::TYPE_ID);
        //销售数量
        $info['sellnum'] = Model_Member_Order::get_sell_num($info['id'], self::TYPE_ID) + (int)$info['bookcount'];
        //产品编号
        $info['series'] = St_Product::product_series($info['id'], self::TYPE_ID);
        //产品图标
        $info['iconlist'] = Product::get_ico_list($info['iconlist']);
        //满意度
        $info['score'] = St_Functions::get_satisfy(self::TYPE_ID, $info['id'], $info['satisfyscore']);

        $info['litpic'] = $this->img_url($info['litpic']);

        $info['carkindname'] = Model_Car_Kind::get_carkindname($info['carkindid']);
        //套餐信息
        $info['suit_info'] = $this->suit($info['id'],$params,$info['use_type']);

        // 供应商信息
        if ($info['supplierlist']) {
            $supplier_shop_service = new Service_Api_Supplier_Shop();
            $info['supplier_info'] = $supplier_shop_service->get_shop_info($info['supplierlist']);
            if (!$info['supplier_info']) {
                $info['supplierlist'] = false;
            }
        }

        //会员折扣
        foreach ($info['suit_info'] as &$item)
        {
            foreach ($item['list'] as $__k=>&$__v)
            {
                $__v['discount_min_price'] = Model_Api_V2_Discount::get_discount($mid, self::TYPE_ID, $id, $__v['price']);
            }
        }
        if ($mid) {
            $info['discount_min_price'] = Model_Api_V2_Discount::get_discount($mid, self::TYPE_ID, $id, $info['price']);
        }
        //租车详情内容
        $params = array(
            'typeid'        => self::TYPE_ID,
            'productinfo'   => $info,
            'onlyrealfield' => 1,
            'pc'            => 0,

        );
        $info['detail_list'] = $this->get_detail_content($params);
        //分销赚取的金额
        if (St_Functions::is_normal_app_install('mobiledistribution')) {
            $info['profit'] = $this->fenxiao_service->get_estimate_profit(self::TYPE_ID,$mid,$info['id'], $info['price']);
        }
        // 积分抵现配置
        $jifenprice_info          = Model_Jifen_Price::get_used_jifentprice($info['jifentprice_id'], self::TYPE_ID);
        $info['jifentprice_info'] = $this->filter_data(array('isopen', 'id', 'toplimit', 'jifentprice'), $jifenprice_info);
        // 预定送积分
        $jifenbook_info         = Model_Jifen::get_used_jifenbook($info['jifenbook_id'], self::TYPE_ID);
        $info['jifenbook_info'] = $this->filter_data(array('isopen', 'value', 'rewardway'), $jifenbook_info);
        //积分评论
        $jifencomment_info         = Model_Jifen::get_used_jifencomment(self::TYPE_ID);
        $info['jifencomment_info'] = $this->filter_data(array('isopen', 'value', 'rewardway'), $jifencomment_info);
        // 更加ID查询可用的优惠券
        if (St_Functions::is_normal_app_install('coupon')) {
            $coupon_list = Model_Coupon::xcx_get_product_coupon_list($info['id'], self::TYPE_ID, $mid);
            $coupons = [];
            foreach ($coupon_list as $coupon) {
                $coupons[] = $this->filter_data(array('id','name'), $coupon);
            }
            $info['coupon_list'] = $coupons;
        }
        //去除不需要字段信息
        unset($info['attrid'],$info['tagword'],$info['keyword'],$info['attrid'],$info['contractid'],$info['bookcount']);
        return $info;

    }

    /**
     * 根据日期获得该套餐列表
     * @param $params
     * @return array
     */
    public function get_suit_list_by_day($params){
        $use_type =  $info = DB::select('use_type')
            ->from('car')
            ->where('id', '=', $params['carid'])
            ->execute()
            ->get('use_type');
        return $this->suit($params['carid'],$params,$use_type);
    }

    /**
     * 产品查询条件
     * @return array
     * User: netman
     * Date: 2023/9/11 17:48
     */
    function query_condition(): array
    {
        $data = array(
            'sort' => array(//排序
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格从低到高'),
                array('id' => 2, 'name' => '价格从高到低'),
                array('id' => 3, 'name' => '销量优先'),
                array('id' => 4, 'name' => '人气推荐')
            ),
            'price' => array('name' => '价格', 'child' => array()),
        );

        //价格
        $data['price']['child'] = $this->get_prices();

        //属性列表
        $data['attribute'] = $this->get_attributes();

        return $data;
    }

    /**
     * 创建订单
     * @param array $params
     * @return array
     * User: netman
     * Date: 2023/9/13 16:24
     */
    function create_order(array $request_param = array()): array
    {
        $mid = $request_param['mid'];
        $member_info = $request_param['member_info'];
        $self_pickup = $request_param['self_pickup'];

        list($car, $suit, $extend_data) = $this->check_order_params($request_param);

        $order             = $this->make_order($request_param, $car, $suit, $extend_data, $member_info);
        $time_desc = $order['time_desc'];
        unset($order['time_desc']);
        $order['memberid'] = $request_param['mid'];

        //优惠券
        $coupon_id = Arr::get($request_param, 'coupon_id', '');
        if ($coupon_id) {
            $coupon_check = Model_Api_V2_Coupon::order_use_coupon_check($coupon_id, $mid, $order);
        }

        // 处理秒杀数据
        $seckill_id = Arr::get($request_param, 'seckill_id', '');
        if ($seckill_id > 0) {
            list($order, $seckill) = $this->make_order_seckill($seckill_id, $order);
        }

        /*附加信息*/
        $params = array(
            'member_card_id' => $params['member_card_id'] ?? 0,
            'card_tourist_id' => $params['card_tourist_id'] ?? 0,
        );

        // 判断拼团是否允许使用会员折扣
        if (isset($extend_data['together_info']['discount_limit'])) {
            if (!in_array(2, $extend_data['together_info']['discount_limit'])) {
                $params['use_member_discount'] = false;
            }
        }

        // 秒杀不使用会员折扣
        if($seckill_id) {
            $params['use_member_discount'] = false;
        }

        //创建订单
        $out = Model_Api_V2_Order::add_order($order, 'Model_Car', $params);
        if ($out['status']) {

            $order_info       = Model_Member_Order::order_info($order['ordersn']);
            $order['orderid'] = $order_info['id'];

            // 优惠券
            if (!empty($coupon_check)) {
                Model_Coupon::add_coupon_order($coupon_check['cid'], $order['ordersn'], $coupon_check['order_total_price'], $coupon_check, $coupon_id);
            }

            //添加红包抵扣
            $envelope_member_id = (int)($params['envelope_member_id']);//红包id
            if (St_Functions::is_normal_app_install('red_envelope') && $envelope_member_id) {
                Model_Order_Envelope::order_use_envelope($envelope_member_id, $order['ordersn'], self::TYPE_ID, $mid);
            }

            // 添加拼团订单
            if (isset($extend_data['together_info'])) {
                Model_Api_V2_Together::add_order($extend_data['together_info'], $order_info);
            }

            //秒杀过来的就添加关联订单
            if (isset($seckill) && $seckill) {
                Model_Seckill::add_seckill_order($order_info, $seckill);
            }

            $time_desc = json_decode($time_desc,true);
            DB::update('member_order')->set(['usedate'=>$time_desc['start_date'],'departdate'=>$time_desc['end_date']])->where('id', '=', $order_info['id'])->execute();

            //订单结算信息表数据更新
            Model_Member_Order_Compute::update($order['ordersn']);

            Hook::trigger('order_created', $order_info);

            // 返回订单信息
            $filter_keys = array('id', 'orderid', 'ordersn', 'pageType', 'typeid', 'status');
            return $this->filter_data($filter_keys, $order_info);
        } else {
            throw new Exception($out['msg']);
        }


    }

    public function get_self_pickup_address($id){
        $self_pickup = DB::select('self_pickup')
                         ->from('car')
                         ->where('id', '=', $id)
                         ->execute()
                         ->get('self_pickup');
        $self_pickup = json_decode($self_pickup,true);
        return $self_pickup;
    }

}